#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file: wechat_mp.py
@time: 2024-07-14 13:58
@desc:
"""
import json

from flask import Blueprint, request, jsonify
from global_scope import get_db
from tools import log_operations
from wechat.phone_info import get_phone_number
from project_model import Lead, Ip
from tools import rate_limit

db = get_db()
wechat_bp = Blueprint('wechat', __name__, url_prefix='/wechat')


@wechat_bp.route('/infos', methods=['POST'])
@log_operations
@rate_limit("100 per minute")
def wechat_infos():
    """
    微信小程序获取用户信息
    :return:
    """
    data = request.get_json()

    # https://qifu-api.baidubce.com/ip/local/geo/v1/district 百度IP地址查询
    location = data.get('location')
    loc_code = data.get('loc_from')
    ip_info = None
    if location:
        ip = location.get('ip'),
        country = location.get("data", {}).get("country"),
        province = location.get("data", {}).get("prov"),
        city = location.get("data", {}).get("city")
        ip_info = Ip.query.filter_by(ip=ip).first()
        if (not ip_info) and ip:
            ip_info = Ip(
                ip=ip, country=country, province=province, city=city,
                from_source=loc_code, li=json.dumps(location, ensure_ascii=False)
            )
            db.session.add(ip_info)
        else:
            ip_info.times += 1
        db.session.commit()

    code = data.get('code')
    pn_from = "微信小程序"
    if code:
        ppn, cc, pn, pi = get_phone_number(code, request.logger, request.trace_logger)
        lead = Lead.query.filter_by(pn=pn).first()
        if not lead:
            ip_list = list()
            if ip_info:
                ip_list.append(ip_info)
            new_lead = Lead(
                from_source=pn_from, ppn=ppn, pn=pn, cc=cc, pi=pi, ips=ip_list)
            db.session.add(new_lead)
            db.session.commit()
        else:
            lead.times += 1
            if all([ip_info.ip != ip.ip for ip in lead.ips]):
                lead.ips.append(ip_info)
            db.session.commit()

    return jsonify({"code": 0, "message": "ok", "data": {}}), 200


@wechat_bp.route('/index/menu', methods=['POST'])
@log_operations
@rate_limit("100 per minute")
def wechat_index_menu():
    data = {
        "menus": [
            {
                "icon": "https://pic.imgdb.cn/item/65cf4d8b9f345e8d036fc7a4.png",
                "classname": "售卖展示",
                "_id": "000001"
            },
            {
                "icon": "https://pic.imgdb.cn/item/65cf4d549f345e8d036efcbf.png",
                "classname": "租赁案例",
                "_id": "000002"
            },
            {
                "icon": "https://pic.imgdb.cn/item/65cf4d2d9f345e8d036e6642.png",
                "classname": "改造案例",
                "_id": "000003"
            },
            {
                "icon": "https://pic.imgdb.cn/item/65cf4d8b9f345e8d036fc7a4.png",
                "classname": "创意方案",
                "_id": "000004"
            }]
    }
    return jsonify({"code": 0, "message": "ok", "data": data}), 200


@wechat_bp.route('/index/introduce', methods=['POST'])
@log_operations
@rate_limit("100 per minute")
def wechat_index_introduce():
    data = {
        "name": "青岛鸿瑞港通货柜介绍",
        "content": [
            "鸿瑞港通货柜（集装箱）销售服务有限公司目前正全力开拓二手集装箱市场，出售出租各种二手集装箱，我司箱源稳 定，箱形，箱况较好，不漏水不透光，所有箱子符合IICL国际集装箱标准制造，满足CW适货标准，质量可靠，坚固，经济实惠！",
            "适用范围出口海运运输，贵重设备运输，工地施工活动房，工厂临时仓库，临时办公用房围；出口海运运输，贵重设 备运输，工地施工活动房，工厂临时仓库，临时办公用房等。",
            "提供尺寸：20GP、40GP、40HC、45HC、冷藏箱、特种箱等； 使用优点：全封闭式钢体结构、安全可靠、坚固、移动方便、可重复使用、价格较临时简易房有明显优势；提供服务：为您提供物美旧 集装箱，旧集装箱改造，集装箱运输；交易原则：价格合 理，诚信交易，服务，信誉； 如有意向，欢迎来电咨询，共创美好未来,欢迎电话咨询选购,朋友圈每天有更新欢迎加我获取更多集装箱 信息。"]
    }

    return jsonify({"code": 0, "message": "ok", "data": data}), 200


@wechat_bp.route('/footer/item', methods=['POST'])
@log_operations
@rate_limit("100 per minute")
def wechat_footer_item():
    data = {
        "name": "青岛鸿瑞港通货柜有限责任公司",
        "address": "山东青岛",
        "cell_center_icon": "https://pic.imgdb.cn/item/65cf57469f345e8d0395cfeb.png",
        "content": {}
    }

    return jsonify({"code": 0, "message": "ok", "data": data}), 200


@wechat_bp.route('/index/banner', methods=['POST'])
@log_operations
@rate_limit("100 per minute")
def wechat_index_banner():
    data = {
        "images": [
            "https://pic.imgdb.cn/item/65cf2b479f345e8d03fc4730.jpg",
            "https://pic.imgdb.cn/item/65cf3a4a9f345e8d032c416d.jpg",
            "https://pic.imgdb.cn/item/65cf3a7f9f345e8d032cf171.jpg"
        ]
    }

    return jsonify({"code": 0, "message": "ok", "data": data}), 200


@wechat_bp.route('/box/detail', methods=['POST'])
@log_operations
@rate_limit("100 per minute")
def wechat_box_detail():
    data = {
        "boxid": "boxid123456",
        "boxtype": "冻柜or干柜",
        "boxsize": "20RF箱体",
        "frontview": "https://pic.imgdb.cn/item/65d304329f345e8d03464205.jpg",
        "rearview": "https://pic.imgdb.cn/item/65d304329f345e8d03464205.jpg",
        "leftview": "https://pic.imgdb.cn/item/65d304329f345e8d03464205.jpg",
        "rightview": "https://pic.imgdb.cn/item/65d304329f345e8d03464205.jpg",
        "insideview": "https://pic.imgdb.cn/item/65d304329f345e8d03464205.jpg",
        "nameplateview": "https://pic.imgdb.cn/item/65d304329f345e8d03464205.jpg",
        "remark": "备注信息",
        "owner": {
            "name": "张三",
            "phone": "13576859635",
            "address": "青岛市黄岛区",
            "remark": "测试信息"
        },
        "carnumber": "123456",
        "carnumberimage": "https://pic.imgdb.cn/item/65cf3a7f9f345e8d032cf171.jpg"
    }

    return jsonify({"code": 0, "message": "ok", "data": data}), 200


@wechat_bp.route('/product/getlist', methods=['POST'])
@log_operations
@rate_limit("100 per minute")
def wechat_product_getlist():
    data = {
        "total": 20,
        "goods": [
            {
                "_id": "1234567",
                "picpath": "https://pic.imgdb.cn/item/65d20e5c9f345e8d03f3d985.jpg",
                "title": "集装箱，冷柜，保温柜1",
                "pronum": "GB123pronum",
                "grade": "优等",
                "year": "2024",
                "weight": "1吨",
                "price": "面议"

            },
            {
                "_id": "2345678",
                "picpath": "https://pic.imgdb.cn/item/65d20e5c9f345e8d03f3d985.jpg",
                "title": "集装箱，冷柜，保温柜2",
                "pronum": "GB123pronum",
                "grade": "优等",
                "year": "2024",
                "weight": "1吨",
                "price": "面议"
            }]
    }

    return jsonify({"code": 0, "message": "ok", "data": data}), 200
